// 云函数入口文件
const cloud = require('wx-server-sdk')
//1，引入支付的三方依赖
const tenpay = require('tenpay');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
//2，配置支付信息
const config = {
  appid: 'wx127dd865e3729ae1',
  mchid: '1619743433',
  partnerKey: '3g2CO9hlB0zwqMGV99Wbe3cTpgOHnNVu',
  pfx: require('fs').readFileSync('apiclient_cert.p12'), 
  notify_url: 'https://mp.weixin.qq.com',
  spbill_create_ip: '127.0.0.1' //这里填这个就可以
};
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  let { type, orderid, money, title, refund_money, refund_orderid } = event;
  //3，初始化支付
  const api = tenpay.init(config);
  if (type == 'pay_money') {
    return await api.getPayParams({
      out_trade_no: orderid,
      body: title,
      total_fee: money, //订单金额(分)
      openid: wxContext.OPENID //付款用户的openid
    });
  } else if (type == 'refund_money') {
    return await api.refund({
      // transaction_id, out_trade_no 二选一
      //transaction_id: orderid,
      out_trade_no: orderid,
      out_refund_no: refund_orderid,
      total_fee: money,
      refund_fee: refund_money
    });
  }

}